package com.heima.admin.service.imp;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.service.AdUserService;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vo.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author stone
 * @description 针对表【ad_user(管理员用户信息表)】的数据库操作Service实现
 * @createDate 2023-02-25 16:54:42
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser>
        implements AdUserService {

    @Override
    @Transactional
    public ResponseResult login(AdUserDTO dto) {
        if (Objects.isNull(dto)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }

        String name = dto.getName();
        String password = dto.getPassword();
        if (StringUtils.isEmpty(name)) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE, "缺少用户名");
        }

        AdUser adUser = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, name));
        if (Objects.isNull(adUser)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "用户名不存在");
        }
        // 用户信息存在则校验密码与状态
        String passwordMd5 = DigestUtils.md5DigestAsHex((password + adUser.getSalt()).getBytes());
        if (!adUser.getPassword().equals(passwordMd5)) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        if (adUser.getStatus() != 9) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        // 设置登录等信息
        adUser.setLoginTime(new Date());
        this.updateById(adUser);

        // 登录校验通过，颁发令牌，返回token与用户信息
        String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));
        AdUserVO userVO = new AdUserVO();

        BeanUtils.copyProperties(adUser, userVO);
        Map<Object, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("user", userVO);

        return ResponseResult.okResult(map);
    }
}




